// 用来检测轨道音量
import {EventEmitter} from "events";

export default class AudioVolume  extends EventEmitter{
  constructor(audioTrack) {
    super();
    if(audioTrack){
      // 1.创建音频上下文
      let audioContext = new AudioContext();// 创建音频上下文
      this.audioContext = audioContext;
      // 2.创建音频分析器节点
      let analyserNode = audioContext.createAnalyser();//音频分析器节点
      this.analyserNode = analyserNode;
      // 3.音频源节点
      const stream = new MediaStream();
      stream.addTrack(audioTrack);
      const mediaStreamAudioSourceNode = audioContext.createMediaStreamSource(stream);
      this.audioTrack = audioTrack;
      this.mediaStreamAudioSourceNode = mediaStreamAudioSourceNode;
      // 4.创建目标节点
      const destinationNode = new MediaStreamAudioDestinationNode(audioContext);
      this.destinationNode = destinationNode;
      mediaStreamAudioSourceNode
        .connect(analyserNode)
        .connect(destinationNode);
    }
  }
  // 数据可视化（时域线形图）
  audioVolumeView(){
    let _this = this;
    let dataArray = new Uint8Array(_this.analyserNode.frequencyBinCount);
    (function viewFun(){
      if(_this.audioTrack&&_this.audioContext.state == "closed"){
        return;
      }
      // 动画（屏幕刷新时执行）
      window.requestAnimationFrame(viewFun);
      // 获取时域数据
      _this.analyserNode.getByteFrequencyData(dataArray)
      let volume = Math.max(...dataArray);
      _this.emit('volume',Math.floor(volume>100?volume:0))
    })();
  }
  // 关闭上下文、音频流
  async close() {
    try{
      /*清空AudioContext*/
      await this.audioContext.close();
    }catch (e) {
      console.error(e);
    }
  }
}
